package com.central.apps.handler.project;

import com.central.app.common.base.BaseHandler;
import com.central.apps.entity.CostAttribute;
import com.central.apps.service.CostAccumulationService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 处理项目成本分配业务逻辑
 *
 * @author lidachao
 * @date 2023/4/7
 */
@Component
@Slf4j
public class ProjectCostAssignHandler extends BaseHandler {

    @Autowired
    private CostAccumulationService costAccumulationService;

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        if(flowNode.getId().equals("complete") && op.isFlag()) {
            // 成本归集
            Map<String, Object> map = op.getVariables();
            CostAttribute costAttribute = new CostAttribute();
            costAttribute.setName(MapUtils.getString(map, "pcadesc"));// 成本单描述
            costAttribute.setProId(MapUtils.getInteger(map, "proid"));// 项目id
            costAttribute.setSubjectNo(MapUtils.getString(map, "subjectno"));// 课题号
            costAttribute.setTotalCost(new BigDecimal(MapUtils.getString(map, "totalcost")));// 总计金额
            costAttribute.setOrderId(MapUtils.getString(map, "id"));// 关联成本单单据id
            costAttribute.setOrderNo(MapUtils.getString(map, "pcanum"));// 关联成本单单据编号
            costAttribute.setCostItemId(MapUtils.getInteger(map, "pbid"));// 预算项id
            costAttribute.setCostSource("成本分配");

            costAccumulationService.costAccumulation(costAttribute);

            // 更新成本单状态
            handlerService.updateBySql("update gq_procostfill set status = '已分配' where id = " + MapUtils.getInteger(map, "pcfid"));
        }

        return null;
    }
}
